import 'package:flutter_admin/api/odoo/dms_userqualifications_odoo_api.dart';
import 'package:flutter_admin/models/odoo/dms_userqualifications.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/odoo/dms_userqualifications/dms_userqualifications_dialog.dart';
import 'package:flutter_admin/pages/odoo/dms_userqualifications/dms_userqualifications_edit.dart';
import 'package:flutter_admin/pages/odoo/dms_userqualifications/dms_userqualifications_file/dms_userqualifications_file_list.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/constants/constant.dart';
import 'package:flutter_admin/utils/utils.dart';

class DmsUserqualificationsList extends StatefulWidget {
  DmsUserqualificationsList({Key? key}) : super(key: key);

  @override
  _DmsUserqualificationsListState createState() =>
      _DmsUserqualificationsListState();
}

class _DmsUserqualificationsListState extends State<DmsUserqualificationsList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'id', asc: false)]);
  DmsUserqualifications dmsUserqualifications = DmsUserqualifications();
  List<DmsUserqualifications> selectedList = [];
  // 部门
  late List<SelectOptionVO> departmentList = [];
  // 证书类别
  late List<SelectOptionVO> certificatetypeList = [];
  @override
  void initState() {
    super.initState();
    var deparment =
        StoreUtil.read(Constant.KEY_CURRENT_USER_INFO)[0]["department_id"];
    dmsUserqualifications.departmentId = deparment[0].toString();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _loadSelectVO();
      _query();
    });
  }

  _loadSelectVO() async {
    departmentList = await DynamicDataApi.getModelSelect(
        model: "hr.department", name: "complete_name");
    certificatetypeList = await DynamicDataApi.getDictList("certificatetype");
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CrySelect(
            width: 280,
            label: '部门',
            dataList: departmentList,
            value: dmsUserqualifications.departmentId,
            onSaved: (v) => {dmsUserqualifications.departmentId = v},
          ),
          CrySelect(
            width: 280,
            label: '证书类别',
            dataList: certificatetypeList,
            value: dmsUserqualifications.certificatetypeId,
            onSaved: (v) => {dmsUserqualifications.certificatetypeId = v},
          ),
          CryInput(
            width: 160,
            label: '证书编号',
            value: dmsUserqualifications.certificateno,
            onSaved: (v) {
              dmsUserqualifications.certificateno = v;
            },
          ),
          CryInput(
            width: 160,
            label: '证书名称',
            value: dmsUserqualifications.certificatename,
            onSaved: (v) {
              dmsUserqualifications.certificatename = v;
            },
          ),
          CryInput(
            width: 160,
            label: '证书持有人',
            value: dmsUserqualifications.holderName,
            onSaved: (v) {
              dmsUserqualifications.holderName = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('证书编号')),
        DataColumn(label: Text('证书名称')),
        DataColumn(label: Text('证书类别')),
        DataColumn(label: Text('部门')),
        DataColumn(label: Text('证书持有人')),
        DataColumn(label: Text('培训日期')),
        DataColumn(label: Text('发证单位')),
        DataColumn(label: Text('发证日期')),
        DataColumn(label: Text('有效期截止日')),
        DataColumn(label: Text('备注')),
        DataColumn(label: Text('创建人')),
        DataColumn(label: Text('创建日期')),
      ],
      getCells: (m) {
        DmsUserqualifications dmsUserqualifications =
            DmsUserqualifications.fromMap(m);
        return [
          DataCell(Text(dmsUserqualifications.certificateno ?? '--')),
          DataCell(Text(dmsUserqualifications.certificatename ?? '--')),
          DataCell(Text(dmsUserqualifications.certificatetypeName ?? '--')),
          DataCell(Text(dmsUserqualifications.departmentName ?? '--')),
          DataCell(Text(dmsUserqualifications.holderName ?? '--')),
          DataCell(Text(dmsUserqualifications.traindate ?? '--')),
          DataCell(Text(dmsUserqualifications.Issuingcompany ?? '--')),
          DataCell(Text(dmsUserqualifications.Issuingdate ?? '--')),
          DataCell(Text(dmsUserqualifications.expirydate ?? '--')),
          DataCell(Text(dmsUserqualifications.remark ?? '--')),
          DataCell(Text(dmsUserqualifications.createUid ?? '--')),
          DataCell(Text(dmsUserqualifications.createDate != ""
              ? Utils.timeUTC(dmsUserqualifications.createDate)
              : '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButtons.add(context, () => _edit(null)),
        CryButtons.edit(context,
            selectedList.length == 1 ? () => _edit(selectedList[0]) : null),
        CryButtons.delete(context,
            selectedList.length != 0 ? () => _delete(selectedList) : null),
        CryButtons.dmsFile(
          context,
          selectedList.length == 1 ? () => _dmsFile(selectedList[0]) : null,
        ),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          isDisplayDesktop(context) ? form : Container(),
          isDisplayDesktop(context) ? buttonBar : Container(),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _edit(DmsUserqualifications? dmsUserqualifications) async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: DmsUserqualificationsEdit(
          dmsUserqualifications: dmsUserqualifications,
        ),
      ),
    ).then((v) {
      if (v != null) {
        if(dmsUserqualifications == null){
          // 新增时回到第一页
          tableKey.currentState?.pageTo(0);
        }
        _loadData();
      }
    });
  }

  _reset() {
    dmsUserqualifications = DmsUserqualifications();
    var deparment =
        StoreUtil.read(Constant.KEY_CURRENT_USER_INFO)[0]["department_id"];
    dmsUserqualifications.departmentId = deparment[0].toString();
    formKey.currentState!.reset();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi =
        await DmsUserqualificationsOdooApi.page(data: {
      "page": page,
      "domainList": dmsUserqualifications.toDomainList(),
    });

    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _delete(List<DmsUserqualifications> selectedList) async {
    cryConfirm(context, S.of(context).confirmDelete, (context) async {
      List ids = selectedList.map((v) {
        return int.parse(v.id!);
      }).toList();
      var result = await DmsUserqualificationsOdooApi.removeByIds(ids);
      if (result.success!) {
        _loadData();
        CryUtils.message(S.of(Cry.context).success);
      }
    });
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: DmsUserqualificationsDialog(),
      ),
    ).then((v) {
      if (v != null) {
        dmsUserqualifications = v;
        _query();
      }
    });
  }

  _dmsFile(DmsUserqualifications dmsUserqualifications) {
    Utils.fullscreenDialog(DmsUserqualificationsFileList(
        dmsUserqualifications: dmsUserqualifications));
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<DmsUserqualifications>((e) => DmsUserqualifications.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.add) {
          _edit(null);
        } else if (v == OperationType.edit) {
          _edit(selectedList[0]);
        } else if (v == OperationType.delete) {
          cryConfirm(context, S.of(context).confirmDelete, (context) async {
            _delete(selectedList);
          });
        } else if (v == OperationType.dmsFile) {
          _dmsFile(selectedList[0]);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.add,
          child: ListTile(
            leading: const Icon(Icons.add),
            title: Text('添加'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.edit),
            enabled: selectedList.length == 1,
            title: Text('修改'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: selectedList.length != 0,
          child: ListTile(
            leading: const Icon(Icons.delete),
            enabled: selectedList.length != 0,
            title: Text('删除'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.dmsFile,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.view_agenda_rounded),
            enabled: selectedList.length == 1,
            title: Text('电子证书'),
          ),
        ),
      ],
    );
  }
}
